package net.adetech.crj.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import net.adetech.crj.dao.ScheduleMapper;
import net.adetech.crj.entity.Schedule;
import net.adetech.crj.entity.ScheduleAmount;
import net.adetech.crj.entity.ScheduleTemplate;
import net.adetech.crj.utils.InnerServiceUtil;
import net.adetech.framework.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service("appointment.getMonthList")
public class MonthListService implements BaseService {
    @Autowired
    ScheduleMapper scheduleMapper;

    @Override
    public Map<String, Object> invoke(Map<String, Object> params) {
        Date start = (Date) params.get("start");
        int offset = (Integer) params.get("offset");
        long hallId = (Long) params.get("hallId");
        String serviceType = (String) params.get("serviceType");

        this.initScheduleData(hallId,serviceType);
        List<Month> monthList = getDayArray(start, offset, serviceType);
        String json = JSON.toJSONString(monthList);
        return InnerServiceUtil.buildResult("monthList", json);
    }

    public JSONObject getMonthJson(Date date) {
        JSONObject result = new JSONObject();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        result.put("year", year);
        result.put("month", month);
        result.put("monthName", year + "年" + month + "月");

        return result;
    }


//    private static int[] TIME_PEROID = {9,  10, 14, 15};


    private Map<Integer, ScheduleTemplate> scheduleTemplateMap;
    private Map<String, Schedule> scheduleMap;
    private Map<String, Schedule> holidayMap;
    private Map<String, Schedule> workingDayMap;
    private Map<String, Schedule> specialDayMap;
    private Map<String, Integer> scheduleAmounMap;

    private void initScheduleData(long hallId,String serviceType) {

        List<ScheduleTemplate> scheduleTemplateList = scheduleMapper.getScheduleTemplateListByHallId(hallId);
        this.scheduleTemplateMap = new HashMap<Integer, ScheduleTemplate>();
        for (ScheduleTemplate template : scheduleTemplateList) {
            this.scheduleTemplateMap.put(template.getDayOfWeek(), template);
        }

        List<Schedule> scheduleList = scheduleMapper.getScheduleListByHallId(hallId);
        this.scheduleMap = new HashMap<String, Schedule>();
        this.holidayMap = new HashMap<String, Schedule>();
        this.workingDayMap = new HashMap<String, Schedule>();
        this.specialDayMap = new HashMap<String, Schedule>();
        for (Schedule schedule : scheduleList) {
            this.scheduleMap.put(schedule.getDayId(), schedule);
            if ("1".equals(schedule.getDayType())) {
                this.holidayMap.put(schedule.getDayId(), schedule);
            } else if ("2".equals(schedule.getDayType())) {
                this.workingDayMap.put(schedule.getDayId(), schedule);
            } else if ("3".equals(schedule.getDayType())) {
                this.specialDayMap.put(schedule.getDayId(), schedule);
            }
        }

        List<ScheduleAmount> scheduleAmountList = new ArrayList<ScheduleAmount>();
        if ("A".equals(serviceType))
        {
            scheduleAmountList = scheduleMapper.getScheduleAmountListByHallId(hallId,serviceType);

        }
        else {
            scheduleAmountList = scheduleMapper.getGroupAmountListByHallId(hallId);

        }
        this.scheduleAmounMap = new HashMap<String, Integer>();
        for (ScheduleAmount amount : scheduleAmountList) {
            this.scheduleAmounMap.put(amount.getTimePeriod(), amount.getAmount());
        }


    }


    private List<Month> getDayArray(Date start, int offset, String serviceType) {


        String startDayId = new SimpleDateFormat("yyyyMMdd").format(start);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);

        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        calendar.add(Calendar.DATE, offset);

        Date end = calendar.getTime();
        String endDayId = new SimpleDateFormat("yyyyMMdd").format(end);
        calendar.add(Calendar.MONTH, 1);
        calendar.set(Calendar.DAY_OF_MONTH, 0);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        Date monthEndDay = calendar.getTime();
        long endTime = monthEndDay.getTime();

        List<Month> monthList = new LinkedList<Month>();
        Map<String, Month> monthMap = new LinkedHashMap<String, Month>();

        try {
            Date monthBeginDate = DateUtils.getFirstDayOfMonth(start);
            calendar.setTime(monthBeginDate);

            while (calendar.getTimeInMillis() < endTime) {
                Date tempDate = calendar.getTime();
                String dayId = new SimpleDateFormat("yyyyMMdd").format(tempDate);
                String monthId = new SimpleDateFormat("yyyyMM").format(tempDate);
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH) + 1;
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                String monthName = year + "年" + month + "月";
                String dayName = year + "年" + month + "月" + day + "日";
                int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);

                Month m;

                //JSONObject monthObject;
                if (monthMap.keySet().contains(monthId)) {
                    m = monthMap.get(monthId);
                } else {
                    m = new Month();
                    m.setYear(year);
                    m.setMonth(month);
                    m.setMonthId(monthId);
                    m.setMonthName(monthName);
                    m.setDayList(new LinkedList<Day>());
                    m.setFirstDayOfWeek(dayOfWeek);
                    m.setAppFlag(false);
                    List<Integer> blankDay = new ArrayList<Integer>();
                    for (int k = 0; k < (dayOfWeek + 5) % 7; k++) {
                        blankDay.add(k);
                    }
                    m.setBlankDayList(blankDay);


                    monthList.add(m);
                    monthMap.put(monthId, m);
                }
                List<Day> dayList = m.getDayList();

                Day d = new Day();
                d.setDayId(dayId);
                d.setDay(day);
                d.setDayName(dayName);


                //不在区间内
                if (Integer.parseInt(dayId) < Integer.parseInt(startDayId) || Integer.parseInt(dayId) > Integer.parseInt(endDayId)) {
                }
                //法定节假日
                else if (this.holidayMap.keySet().contains(dayId)) {
                }
                //工作日
                else {

                    int startHour = 0;
                    if (Integer.parseInt(dayId) == Integer.parseInt(startDayId)) {
                        startHour = Integer.parseInt(new SimpleDateFormat("HHmm").format(new Date()));
                    }


                    int[] amountArray = new int[4];
                    for (int i = 0; i < amountArray.length; i++) {
                        String timePeriod = dayId + "_" + i;
                        Integer amount = this.scheduleAmounMap.get(timePeriod);
                        if (amount == null) {
                            amount = 0;
                        } else {
                            System.out.println(timePeriod);
                        }
                        amountArray[i] = amount;
                    }


                    if ("A".equals(serviceType)) {
                        //调休日
                        if (this.specialDayMap.keySet().contains(dayId)) {
                            Schedule schedule = this.specialDayMap.get(dayId);
                            if (900 >= startHour) {
                                d.timeList[0] = schedule.getCount1() - amountArray[0];
                            }
                            if (1030 >= startHour) {
                                d.timeList[1] = schedule.getCount2() - amountArray[1];
                            }
                            if (1400 >= startHour) {
                                d.timeList[2] = schedule.getCount3() - amountArray[2];
                            }
                            if (1530 >= startHour) {
                                d.timeList[3] = schedule.getCount4() - amountArray[3];
                            }

                        }
                        //普通时间
                        else {
                            ScheduleTemplate template = scheduleTemplateMap.get(dayOfWeek);

                            if (900 >= startHour) {
                                d.timeList[0] = template.getCount1() - amountArray[0];
                            }
                            if (1030 >= startHour) {
                                d.timeList[1] = template.getCount2() - amountArray[1];
                            }
                            if (1400 >= startHour) {
                                d.timeList[2] = template.getCount3() - amountArray[2];
                            }
                            if (1530 >= startHour) {
                                d.timeList[3] = template.getCount4() - amountArray[3];
                            }

                        }
                    } else if ("B".equals(serviceType)||"M".equals(serviceType)) {
                        //调休日
                        //调休日
                        if (this.specialDayMap.keySet().contains(dayId)) {
                            Schedule schedule = this.specialDayMap.get(dayId);
                            if (900 >= startHour) {
                                d.timeList[0] = schedule.getCount5() - amountArray[0];
                            }
                            if (1030 >= startHour) {
                                d.timeList[1] = schedule.getCount6() - amountArray[1];
                            }
                            if (1400 >= startHour) {
                                d.timeList[2] = schedule.getCount7() - amountArray[2];
                            }
                            if (1530 >= startHour) {
                                d.timeList[3] = schedule.getCount8() - amountArray[3];
                            }

                        }
                        //普通时间
                        else {
                            ScheduleTemplate template = scheduleTemplateMap.get(dayOfWeek);

                            if (900 >= startHour) {
                                d.timeList[0] = template.getCount5() - amountArray[0];
                            }
                            if (1030 >= startHour) {
                                d.timeList[1] = template.getCount6() - amountArray[1];
                            }
                            if (1400 >= startHour) {
                                d.timeList[2] = template.getCount7() - amountArray[2];
                            }
                            if (1530 >= startHour) {
                                d.timeList[3] = template.getCount8() - amountArray[3];
                            }

                        }
                    }
                }


                dayList.add(d);
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                //System.out.println(calendar.getTime());
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        for (int i = 0; i < monthList.size(); i++) {
            if (i == 0) {
                monthList.get(i).setHasPrev(false);
            } else {
                monthList.get(i).setHasPrev(true);
            }

            if (i >= monthList.size() - 1) {
                monthList.get(i).setHasNext(false);
            } else {
                monthList.get(i).setHasNext(true);
            }
        }

        return monthList;
    }


    private List<ScheduleTemplate> initScheduleTemplateList() {
        return null;
    }

    private Map<Integer, ScheduleTemplate> initScheduleTemplateMap(List<ScheduleTemplate> scheduleTemplateList) {
        Map<Integer, ScheduleTemplate> scheduleTemplateMap = new HashMap<Integer, ScheduleTemplate>();
        for (ScheduleTemplate template : scheduleTemplateList
                ) {
            scheduleTemplateMap.put(template.getDayOfWeek(), template);
        }
        return scheduleTemplateMap;
    }

    private List<Schedule> initScheduleList() {
        return null;
    }

    private Map<String, Schedule> initScheduleMap(List<Schedule> scheduleList) {
        Map<String, Schedule> scheduleMap = new HashMap<String, Schedule>();
        for (Schedule schedule : scheduleList
                ) {
            scheduleMap.put(schedule.getDayId(), schedule);
        }
        return scheduleMap;
    }

    private class Month {
        int month;
        int year;
        String monthId;
        String monthName;
        boolean hasNext;
        boolean hasPrev;
        boolean appFlag;
        int firstDayOfWeek;
        List<Integer> blankDayList = new LinkedList<Integer>();
        List<Day> dayList = new LinkedList<Day>();

        public int getMonth() {
            return month;
        }

        public void setMonth(int month) {
            this.month = month;
        }

        public int getYear() {
            return year;
        }

        public void setYear(int year) {
            this.year = year;
        }

        public String getMonthId() {
            return monthId;
        }

        public void setMonthId(String monthId) {
            this.monthId = monthId;
        }

        public String getMonthName() {
            return monthName;
        }

        public void setMonthName(String monthName) {
            this.monthName = monthName;
        }

        public boolean isHasNext() {
            return hasNext;
        }

        public void setHasNext(boolean hasNext) {
            this.hasNext = hasNext;
        }

        public boolean isHasPrev() {
            return hasPrev;
        }

        public void setHasPrev(boolean hasPrev) {
            this.hasPrev = hasPrev;
        }

        public boolean isAppFlag() {
            return appFlag;
        }

        public void setAppFlag(boolean appFlag) {
            this.appFlag = appFlag;
        }

        public int getFirstDayOfWeek() {
            return firstDayOfWeek;
        }

        public void setFirstDayOfWeek(int firstDayOfWeek) {
            this.firstDayOfWeek = firstDayOfWeek;
        }

        public List<Integer> getBlankDayList() {
            return blankDayList;
        }

        public void setBlankDayList(List<Integer> blankDayList) {
            this.blankDayList = blankDayList;
        }

        public List<Day> getDayList() {
            return dayList;
        }

        public void setDayList(List<Day> dayList) {
            this.dayList = dayList;
        }

        public void addBlankDay(int day) {
            this.blankDayList.add(day);
        }

        public void addDay(Day day) {
            this.dayList.add(day);
        }

    }

    private class Day {

        int[] timeList = new int[4];
        String dayName;
        String dayId;
        int day;

        public int[] getTimeList() {
            return timeList;
        }

        public void setTimeList(int[] timeList) {
            this.timeList = timeList;
        }

        public String getDayName() {
            return dayName;
        }

        public void setDayName(String dayName) {
            this.dayName = dayName;
        }

        public String getDayId() {
            return dayId;
        }

        public void setDayId(String dayId) {
            this.dayId = dayId;
        }

        public int getDay() {
            return day;
        }

        public void setDay(int day) {
            this.day = day;
        }

        public boolean isAppFlag() {
            int sum = 0;
            for (int amount : this.timeList
                    ) {
                sum += amount;
            }
            return sum > 0;
        }


    }
}
